<template>
  <div class="container">
    <!-- 状态栏 -->
    <div class="status-bar">
      <div class="app-info">
        <img class="app-icon" src="../assets/app.png" alt="应用图标">
        <span class="app-title">{{ appTitle }}</span>

        <div class="window-controls"
             style="left: 260px;background-color: #e5e5e5;position: absolute;height: 100%;padding: 0 50px">
          <button style="background-color: #e5e5e5;" @click="config" title="配置" class="control-btn">
            配置
          </button>
        </div>
      </div>


      <!-- 窗口控制按钮 -->
      <div class="window-controls">

        <button @click="minimizeWindow" class="control-btn" title="最小化">
          <img src="../assets/window_min.png" alt="最小化">
        </button>
        <button @click="toggleMaximize" class="control-btn" title="">
          <img src="../assets/window_add.png" alt="">
        </button>
        <button @click="closeWindow" class="control-btn close-btn" title="关闭">
          <img src="../assets/window_close.png" alt="关闭">
        </button>
      </div>
    </div>

    <!-- 应用内容 -->
    <el-row class="app-content">
      <el-col :span="14" class="left-panel" style="height: 100%">
        <div style="height: 100%; padding: 10px; background: white; display: flex; flex-direction: column;">

          <div class="batch-actions" style="text-align: left">

            <!-- 第一行：关键词输入 -->
            <el-row :gutter="10" class="action-row">
              <el-col :span="24">
                <el-input
                    v-model="newKeywords"
                    placeholder="输入要绑定的关键词（多个关键词用顿号、分隔）"
                    clearable
                    class="keyword-input">
                </el-input>
              </el-col>
            </el-row>

            <!-- 第二行：设备选择 -->
            <el-row :gutter="35" class="action-row">
              <el-col :span="19">
                <el-select
                    v-model="selectedAction"
                    placeholder="选择目标设备"
                    clearable
                    filterable
                    class="device-select">
                  <el-option
                      v-for="(action, idx) in devices"
                      :key="idx"
                      :label="action"
                      :value="action">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button
                    type="primary"
                    @click="addCollectionData"
                >
                  添加采集任务
                </el-button>
              </el-col>
            </el-row>
            <el-row :gutter="35" class="action-row">
              <el-col :span="24">
                <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入私信回复内容"
                    v-model="textarea">
                </el-input>
              </el-col>
            </el-row>
          </div>
          <div style="flex: 1; overflow-y: auto">
            <el-table
                :data="deviceList"
                stripe
                style="width: 100%;"
                height="100%">

              <el-table-column
                  label="序号"
                  width="80"
                  align="center">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>

              <el-table-column
                  prop="ip"
                  label="设备IP"
                  width="150"
                  sortable>
                <template #default="{ row }">
                  <el-tag effect="plain">{{ row.ip }}</el-tag>
                </template>
              </el-table-column>

              <el-table-column
                  prop="keywords"
                  label="关键字">
                <template #default="{ row }">
                  <el-tooltip
                      v-for="(kw, idx) in row.keywords.split(',')"
                      :key="idx"
                      :content="kw"
                      placement="top">
                    <el-tag class="keyword-tag">{{ kw }}</el-tag>
                  </el-tooltip>
                </template>
              </el-table-column>

              <el-table-column
                  prop="count"
                  width="120"
                  label="采集数量">
                <template #default="{ row }">
                  <el-input v-model="row.count" type="number"></el-input>
                </template>
              </el-table-column>

              <el-table-column
                  prop="deviceStatus"
                  width="150"
                  align="center"
                  label="设备状态">
                <template #default="{ row }">
                  <el-tag type="primary" v-if="row.deviceStatus==0">设备连接正常</el-tag>
                  <el-tag type="danger" v-if="row.deviceStatus==1">设备连接异常</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                  label="操作"
                  width="140"
                  align="center"
                  fixed="right">
                <template #default="{ row,$index}">
                  <el-button-group>
                    <el-button v-if="row.status==0"
                               size="small"
                               type="primary"
                               @click="startTask(row,$index)"
                               icon="Edit">
                      开始采集
                    </el-button>
                    <el-button v-if="row.status==1"
                               size="small"
                               type="warning"
                               icon="Edit">
                      采集中
                    </el-button>
                    <el-button v-if="row.status==2"
                               size="small"
                               type="info"
                               icon="Edit">
                      已结束
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>

            </el-table>
          </div>
        </div>
      </el-col>

      <el-col :span="10" class="center-panel">
        <el-card shadow="never">
          <template #header>
            <h3>采集结果</h3>
          </template>
          <div>
            <el-table
                :data="filteredLogs"
                stripe
                style="width: 100%"
                height="calc(100vh - 220px)"
                v-loading="loading">

              <el-table-column
                  prop="timestamp"
                  label="时间"
                  width="150"
                  sortable>
                <template #default="{ row }">
                  {{ row.timestamp }}
                </template>
              </el-table-column>

              <el-table-column
                  prop="deviceName"
                  label="设备"
                  width="130"
                  sortable>
              </el-table-column>

              <el-table-column
                  prop="keyword"
                  label="关键字"
                  width="120">
                <template #default="{ row }">
                  {{ row.keyword }}
                </template>
              </el-table-column>

              <el-table-column
                  prop="step"
                  label="线索"
                  width="120">
                <template #default="{ row }">
                  <el-tag
                      type="success"> {{ row.info }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column
                  prop="data"
                  label="数据">
                <template #default="{ row }">
                  <el-popover
                      placement="top-start"
                      trigger="hover"
                      width="300">
                    <template #reference>
                      {{ row.data }}
                    </template>
                    <pre class="log-data-preview">{{ JSON.stringify(row.data, null, 2) }}</pre>
                  </el-popover>
                </template>
              </el-table-column>

            </el-table>

          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
        title="设备添加"
        :visible.sync="dialogVisible"
        width="45%"
        :before-close="handleClose">
      <div
          style="border: 1px solid #ebeef5; border-radius: 4px; padding: 12px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);">
        <el-tag
            style="margin-left: 10px"
            v-for="tag in devices"
            :key="tag"
            closable
            @close="handleDelete(index)"
        >
          {{ tag }}
        </el-tag>
      </div>
      <div>

        <el-row :gutter="10" class="action-row" style="margin-top: 30px;text-align: left">
          <el-col :span="8">
            <el-input
                v-model="textDeviceIp"
                type="text"
                placeholder="请输入设备IP"
                style="width: 100%;">
            </el-input>
          </el-col>
          <el-button type="primary"
                     @click="addDeviceIp">添加
          </el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {get, post} from '../utils/http'

import wechatAutomation from '../utils/wechatAutomation';

export default {
  name: 'index',
  props: {},
  components: {},
  data() {
    return {
      appTitle: "IMAI - WORK 数据采集",
      deviceList: [{
        ip: '10.88.80.91', keywords: 'AIGC、AI数字人',
        count: 200, status: 0, deviceStatus: 0
      }],
      devices: [
        '10.88.80.91'
      ],
      textDeviceIp: "",
      textarea: "",
      date_value: "",
      selectedAction: "",
      loading: false,
      newKeywords: "",
      filteredLogs: [],
      dialogVisible: false
    }
  },
  computed: {},
  // 在 Vue 组件中注册监听器
  created() {
    this.date_value = new Date().toLocaleString()
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    handleDelete(index) {
      this.devices.splice(index, 1);  // 从数组中移除对应项
      this.$message.success("已删除设备 IP");
    },
    isValidIP(ip) {
      // IPv4 正则（简单版，匹配 0.0.0.0 ~ 255.255.255.255）
      const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      return ipv4Regex.test(ip);
    },
    addDeviceIp() {
      if (!this.textDeviceIp) {
        this.$message.error("IP 地址不能为空！");
        return;
      }

      if (!this.isValidIP(this.textDeviceIp)) {
        this.$message.error("IP 地址格式不正确！");
        return;
      }

      if (this.devices.includes(this.textDeviceIp)) {
        this.$message.warning("该 IP 已存在！");
        return;
      }

      this.devices.push(this.textDeviceIp);
      this.textDeviceIp = ""; // 清空输入框
    },
    config() {
      this.dialogVisible = true
    },
    addCollectionData() {
      if (this.selectedAction.length == "" || this.newKeywords.length == "") {
        this.$message.error('请填写关键字和选择目标设备')
        return
      }
      let obj = {
        ip: this.selectedAction, keywords: this.newKeywords,
        deviceStatus: 0, count: 200, status: 0
      }
      this.deviceList.push(obj)
    },
    toggleMaximize() {

    },
    minimizeWindow() {
      let obj = {
        name: "",
        data: "min"
      }
      window.myApi.mainWindow(obj);
    },
    closeWindow() {
      let obj = {
        name: "",
        data: "close"
      }
      window.myApi.mainWindow(obj);
    },
    showDeviceDetail(device) {

    },
    getDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');  // Months are 0-indexed, so add 1
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedTime

    },
    async startTask(device, index) {
      console.log(device, index)
      try {

        // const params = {"packageName": "com.tencent.mm"}
        // const res = await get("http://" + device.ip + ":18080/api/stopPackage",params)

        device.status = 1
        this.deviceList.splice(index, 1, device)

        // this.$message.success(`${device.ip} 设备启动成功`);


        this.weChatAutomation = new wechatAutomation(
            device.ip,
            device.keywords.split("、"),
            5,
            (tags, log) => {
              console.log("weChatAutomation", tags, log)
              if (tags == 0 && log.type == 0) {
                //数据日志
                let obj = {
                  timestamp: this.getDate(),
                  deviceName: log.device,
                  keyword: log.keyword,
                  data: log.content,
                  info: log.info
                }
                this.filteredLogs.push(obj)
              } else if (tags == 1) {

                const index = this.deviceList.findIndex(item => item.ip === log.ip);
                console.log("weChatAutomation", log, index)
                if (index !== -1) {
                  const updatedItem = this.deviceList[index]
                  updatedItem.deviceStatus = 1;
                  updatedItem.status = 0;
                  this.deviceList.splice(index, 1, updatedItem);
                }

              } else if (tags == 2) {

                const index = this.deviceList.findIndex(item => item.ip === log.ip);
                console.log("weChatAutomation", log, index)
                if (index !== -1) {
                  const updatedItem = this.deviceList[index]
                  updatedItem.deviceStatus = 0;
                  this.deviceList.splice(index, 1, updatedItem);
                }

              }
            }
        );

        this.deviceList.splice(index, 1, device)

        this.weChatAutomation.init()


      } catch (error) {
        console.log(error.message)
        this.$message.error(`启动失败: ${error.message}`);
      }
    },
    exportData() {

    }
  },
  mounted() {

  }
}
</script>

<style scoped>
h3, p, div {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.status-bar {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 48px;
  background-color: #f0f0f0;
  -webkit-app-region: drag; /* 允许拖动 */
  padding: 0 0px 0 10px;
  border-bottom: 1px solid #ddd;
}

.app-info {
  display: flex;
  align-items: center;
}

.app-icon {
  width: 32px;
  height: 32px;
  margin-right: 8px;
}

.app-title {
  font-size: 15px;
  color: #333;
}

.window-controls {
  display: flex;
  -webkit-app-region: no-drag; /* 禁止拖动 */
}

.control-btn {
  margin: 0px 5px;
  border: none;
}

.control-btn img {
  padding: 5px 0;
  width: 20px;
  height: 20px;
  border: none;
  background: transparent;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-btn:hover {
  background-color: #e5e5e5;
}

.close-btn:hover {
  background-color: #e81123;
}

/* 三栏布局样式 */
.app-content {
  flex: 1;
  margin: 0 !important;
  height: calc(100vh - 60px);
}

.left-panel, .center-panel, .right-panel {
  height: 100%;
  padding: 10px;
}

.left-panel {
  background-color: #f9f9f9;
  border-right: 1px solid #e6e6e6;
}

.center-panel {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.right-panel {
  background-color: #f5f5f5;
}

/* 调整 Element UI 卡片样式 */
.el-card {
  height: 100%;
  border: none;
}

.el-card__header {
  padding: 12px 20px;
  border-bottom: 1px solid #ebeef5;
}

.el-card__body {
  padding: 15px;
  height: calc(100% - 57px);
  overflow-y: auto;
}

.batch-actions {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-top: 15px;
}

.batch-actions .action-row {
  margin-bottom: 15px;
  align-items: center;
}

.batch-actions .action-row:last-child {
  margin-bottom: 0;
}

.batch-actions .keyword-input .el-input__inner {
  padding-left: 35px;
}

.batch-actions .keyword-input .el-input__prefix {
  left: 10px;
  color: #409eff; /* 替换 var(--el-color-primary) */
}

.batch-actions .device-select {
  width: 100%;
}

.batch-actions .action-btn {
  width: 100%;
}

.batch-actions .btn-group {
  display: flex;
  justify-content: flex-end;
}

.batch-actions .calendar-row .el-calendar {
  border: 1px solid #dcdfe6; /* 替换 var(--el-border-color) */
  border-radius: 4px;
}

.batch-actions .calendar-row .el-calendar__header {
  padding: 10px;
}

.batch-actions .export-col {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  padding-left: 15px;
}

.batch-actions .export-col .export-btn {
  width: 100%;
  margin-bottom: 10px;
}

.batch-actions .export-col .export-btn:last-child {
  margin-bottom: 0;
}

.batch-actions .is-selected {
  color: #409eff; /* 替换 var(--el-color-primary) */
  font-weight: bold;
}

/* 关键CSS */
.card-container {
  height: 100vh; /* 或使用 calc(100vh - 其他元素高度) */
  padding: 20px; /* 可选内边距 */
}

.full-height-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 修复Element UI卡片内部滚动问题 */
.full-height-card .el-card__body {
  height: 100%;
  overflow: auto;
}

:deep(.el-card__body,.el-card) {
  height: 100%
}
</style>
